<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="表单名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入表单名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="应用名称" prop="sheetName">
            <el-input v-model="queryParams.sheetName" placeholder="请输入应用名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['system:sheetForm:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Plus" @click="toSheetFormDiy()" v-hasPermi="['system:sheetForm:add']">表单设计</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        v-loading="loading"
        :data="sheetFormList"
        row-key="sheetFormId"
        :default-expand-all="isExpandAll"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        ref="sheetFormTableRef"
        highlight-current-row
        @row-click="rowClick"
      >
        <el-table-column label="表单名称" align="center" prop="name" />
        <el-table-column label="显示名称" align="center" prop="showName" />
        <el-table-column label="页签" align="center" prop="tabName" />
        <el-table-column label="应用ID" align="center" prop="sheetId" />
        <el-table-column label="应用名称" align="center" prop="sheetName" />
        <el-table-column label="排序号" align="center" prop="sort" />
        <el-table-column label="显示方式" align="center" prop="showType">
          <template #default="scope">
            <dict-tag :options="form_show_type" :value="scope.row.showType" />
          </template>
        </el-table-column>
        <el-table-column label="是否启用" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:sheetForm:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['system:sheetForm:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:sheetForm:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改表单管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="sheetFormFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级表单" prop="pid">
          <el-tree-select
            v-model="form.pid"
            :data="sheetFormOptions"
            :props="{ value: 'sheetFormId', label: 'name', children: 'children' }"
            value-key="sheetFormId"
            placeholder="请选择上级表单"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="表单名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入表单名称" />
        </el-form-item>
        <el-form-item label="显示名称" prop="showName">
          <el-input v-model="form.showName" placeholder="请输入显示名称" />
        </el-form-item>
        <el-form-item label="页签" prop="tabName">
          <el-input v-model="form.tabName" placeholder="请输入页签" />
        </el-form-item>
        <el-form-item label="应用" prop="sheetId">
          <el-tree-select
            v-model="form.sheetId"
            :data="sheetOptions"
            :props="{ value: 'sheetId', label: 'name', children: 'children' }"
            :filter-node-method="filterNodeMethod"
            value-key="sheetId"
            placeholder="选择应用"
            check-strictly
            filterable
          />
        </el-form-item>
        <el-form-item label="显示方式" prop="showType">
          <el-radio-group v-model="form.showType">
            <el-radio
              v-for="dict in form_show_type"
              :key="dict.value"
              :disabled="form.pid == 0"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SheetForm" lang="ts">
import { listSheetForm, getSheetForm, delSheetForm, addSheetForm, updateSheetForm } from '@/api/sheet/sheetForm';
import { SheetFormVO, SheetFormQuery, SheetFormForm } from '@/api/sheet/sheetForm/types';
import {listSheet,findLabelById} from "@/api/sheet/sheet";
const router = useRouter();

type SheetFormOption = {
  sheetFormId: number;
  name: string;
  children?: SheetFormOption[];
}

interface SheetOptionsType {
  sheetId: number | string;
  name: string;
  children: SheetOptionsType[] | undefined;
}

const sheetOptions = ref<SheetOptionsType[]>([]);
const filterNodeMethod = (value : string | number, data: any) => data.name.includes(value)

/** 查询应用下拉树结构 */
const getSheetTreeselect = async () => {
  sheetOptions.value = []
  const response = await listSheet();
  const sheet: SheetOptionsType = { sheetId: 0, name: "主类目", children: [] }
  sheet.children = proxy?.handleTree<SheetOptionsType>(response.data, "sheetId", "pid")
  sheetOptions.value.push(sheet)
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;;


const sheetFormList = ref<SheetFormVO[]>([]);
const sheetFormOptions = ref<SheetFormOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const sheetFormFormRef = ref<ElFormInstance>();
const sheetFormTableRef = ref<ElTableInstance>()

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});


const initFormData: SheetFormForm = {
    sheetFormId: undefined,
    pid: undefined,
    name: undefined,
    tabName: undefined,
    sheetId: undefined,
    sheetName: undefined,
    sort: undefined,
    showType: 1,
    status: 'Y',
    remark: undefined,
}

const data = reactive<PageData<SheetFormForm, SheetFormQuery>>({
  form: {...initFormData},
  queryParams: {
    pid: undefined,
    name: undefined,
    sheetId: undefined,
    sheetName: undefined,
    sort: undefined,
    showType: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    name: [
      { required: true, message: "表单名称不能为空", trigger: "blur" }
    ],
    sheetId: [
      { required: true, message: "应用不能为空", trigger: "blur" }
    ],
    sort: [
      { required: true, message: "排序号不能为空", trigger: "blur" }
    ],
    showType: [
      { required: true, message: "请选择显示方式", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

const { sys_yes_no,form_show_type } = toRefs<any>(proxy?.useDict("sys_yes_no","form_show_type"));

const sheetFormId = ref<any>("");

/** 查询表单管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSheetForm(queryParams.value);
  const data = proxy?.handleTree<SheetFormVO>(res.data, "sheetFormId", "pid");
  if (data) {
    sheetFormList.value = data;
    loading.value = false;
  }
}

/** 查询表单管理下拉树结构 */
const getTreeselect = async () => {
  const res = await listSheetForm();
  sheetFormOptions.value = [];
  const data: SheetFormOption = { sheetFormId: 0, name: '顶级节点', children: [] };
  data.children = proxy?.handleTree<SheetFormOption>(res.data, "sheetFormId", "pid");
  sheetFormOptions.value.push(data);
}

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
}

// 表单重置
const reset = () => {
  form.value = {...initFormData}
  sheetFormFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 新增按钮操作 */
const handleAdd = (row?: SheetFormVO) => {
  reset();
  getTreeselect();
  getSheetTreeselect();
  if (row != null && row.sheetFormId) {
      form.value.pid = row.sheetFormId;
  } else {
      form.value.pid = 0;
  }
  dialog.visible = true;
  dialog.title = "添加表单管理";
}

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(sheetFormList.value, isExpandAll.value)
}

/** 展开/折叠操作 */
const toggleExpandAll = (data: SheetFormVO[], status: boolean) => {
  data.forEach((item) => {
    sheetFormTableRef.value?.toggleRowExpansion(item, status)
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
  })
}

/** 修改按钮操作 */
const handleUpdate = async (row: SheetFormVO) => {
  reset();
  await getTreeselect();
  await getSheetTreeselect();
  if (row != null) {
    form.value.pid = row.pid;
  }
  const res = await getSheetForm(row.sheetFormId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改表单管理";
}

/** 提交按钮 */
const submitForm = () => {
  sheetFormFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      let sheetId = form.value.sheetId;
      if (sheetId){
        let sheetName = await findLabelById(sheetId,sheetOptions.value);
        if (sheetName){
          form.value.sheetName = sheetName;
        }
      }
      if (form.value.sheetFormId) {
        await updateSheetForm(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addSheetForm(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row: SheetFormVO) => {
  await proxy?.$modal.confirm('是否确认删除表单名称为"' + row.name + '"的数据项？');
  loading.value = true;
  await delSheetForm(row.sheetFormId).finally(() => loading.value = false);
  await getList();
  proxy?.$modal.msgSuccess("删除成功");
}


/** 表单设计操作 */
const toSheetFormDiy = () => {
  console.info(sheetFormId.value)
  router.push("/sheet/sheetField/form");
}

/** 点击表格操作 */
const rowClick = (row?: SheetFormVO) => {
  sheetFormId.value = row?.sheetFormId;
}

onMounted(() => {
  getList();
});
</script>
